package book;

import com.bit.utils.FileUtils;
import constant.Constant;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 32309
 * Date: 2025-07-17
 * Time: 22:05
 */
public class AnalyzingBorrowedBook {
    public void writeID(BorrowedUidAndBookId[] ids, String filename) {
        // 判断当前数组的真是数据
        int count = 0;
        for (int i = 0; i < ids.length; i++) {
            if (ids[i] != null) {
                count++;
            }
        }
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < count; i++) {
            stringBuilder.append(ids[i].toStr());
            if (i != count - 1) {
                stringBuilder.append("\n");
            }
        }
        FileUtils.writeFile(stringBuilder.toString(), filename);
    }

    public BorrowedUidAndBookId[] loadID(String filename) {
        String file = FileUtils.readFile(filename);
        if (file == null || file.isEmpty()) {
            return null;
        }

        String[] id = file.split("\n");
        BorrowedUidAndBookId[] borrowedUidAndBookIds = new BorrowedUidAndBookId[id.length];
        for (int i = 0; i < id.length; i++) {
            borrowedUidAndBookIds[i] = toID(id[i]);
        }
        return borrowedUidAndBookIds;
    }

    private BorrowedUidAndBookId toID(String file) {
        String[] id = file.split(",");
        int userID = Integer.parseInt(id[0]);
        int bookID = Integer.parseInt(id[1]);
        String name = id[2];

        BorrowedUidAndBookId borrowedUidAndBookId = new BorrowedUidAndBookId(userID,bookID,name);
        return borrowedUidAndBookId;
    }
}
